package com.leonzhangxf.spel.reference;

import org.springframework.expression.ExpressionParser;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;

/**
 * Expression templating
 * <p>
 * Expression templates allow mixing literal text with one or more evaluation blocks.
 * Each evaluation block is delimited with prefix and suffix characters that you can define.
 * A common choice is to use #{ } as the delimiters.
 *
 * @author leonzhangxf
 * @date 20190427
 * @see TemplateParserContext
 */
public class ExpressionTemplating {

    public static void main(String[] args) {
        ExpressionParser parser = new SpelExpressionParser();

        String randomPhrase = parser.parseExpression(
            "random number is #{T(java.lang.Math).random()}",
            new TemplateParserContext()).getValue(String.class);
        System.out.println(randomPhrase);

        // The string is evaluated by concatenating the literal text 'random number is ' with the result of evaluating
        // the expression inside the #{ } delimiter (in this case, the result of calling that random() method).
        // The second argument to the parseExpression() method is of the type ParserContext.
        // The ParserContext interface is used to influence how the expression is parsed in order to
        // support the expression templating functionality.
    }
}
